class MyBlockingQueue {
    private int[] items = new int[1000];
    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;
    //入队列
    synchronized public void put(int elem)throws InterruptedException{
        while (size == items.length){
            //队列满了，插入失败
            this.wait();
        }
        //把新元素放在tail所在位置
        items[tail] = elem;
        tail++;//将指针后移一位
        //如果tail指针到达末尾，就让tail指针从头再来
        if (tail == items.length){
            tail = 0;
        }
        size++;
        this.notify();
    }
    synchronized public Integer take()throws InterruptedException{
        while (size == 0) {
            //如果队列为空，则阻塞等待
            this.wait();
        }
        int value = items[head];
        head++;
        if (head == items.length) {
            head = 0;
        }
        size--;
        this.notify();
        return value;
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        // 消费者
        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    int value = queue.take();
                    System.out.println("消费: " + value);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 生产者
        Thread t2 = new Thread(() -> {
            int value = 0;
            while (true) {
                try {
                    System.out.println("生产: " + value);
                    queue.put(value);
                    value++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();


        System.out.println("hello");
    }
}
